/*
 * @FilePath: http.ts
 * @Author: jack
 * @Date: 2024-06-20 19:11:15
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-05-21 15:44:36
 * Copyright: 2024 xxxTech CO.,LTD. All Rights Reserved.
 * @Descripttion: 
 */

/* eslint-disable no-undef */
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { watch } from 'vue'
import router from '../router/index'
import { PiniaStore } from '../store'
/**
 * http请求工具类
 *
 * 请求拦截器 负责将客户端标识token值存储并放置在头部提交给服务端
 *
 * 响应拦截器 负责全局处理业务请求的网络或者业务错误
 */
// 创建axios的实例
// 环境的切换
if (import.meta.env.MODE === 'development') {
    axios.defaults.baseURL = '/DataVisual' // 开发环境
} else if (import.meta.env.MODE === 'debug') {
    axios.defaults.baseURL = '' // 调试环境
} else if (import.meta.env.MODE === 'production') {
    axios.defaults.baseURL = '/DataVisual' // 生产环境
}

// axios.defaults.timeout = 600000
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 请求拦截
axios.interceptors.request.use((config: any) => {
    if (router.currentRoute.value.fullPath !== '/HomeView') {
        if (window.sessionStorage.getItem('Token')) {
            config.headers.accessToken = window.sessionStorage.getItem('Token')
        }
    } else {
        if (window.sessionStorage.getItem('ScreenToken')) {
            config.headers.ScreenAccessToken = window.sessionStorage.getItem('ScreenToken')
            config.headers.tokenkey = window.sessionStorage.getItem('tokenkey')
        }
    }
    return config;
}, (err: any) => {
    Promise.reject(err)
})
// 响应拦截
axios.interceptors.response.use((config?: any) => {
    return config
}, async (err: any) => {
    console.log(router.currentRoute, 'jinlial')
    if (router.currentRoute.value.fullPath !== '/HomeView') {
        ElMessage.error(err.response.data.message)
        if (err.response) {
            switch (err.response.status) {
                case 401:
                    // 返回 401 清除token信息并跳转到登录页面
                    setTimeout(() => {
                        router.push({ path: '/login' })
                        window.sessionStorage.removeItem('Token')
                    }, 1000)
            }
        }
        return Promise.reject(err.response.data.msg)   // 返回接口返回的错误信息
    } else {
        const originalRequest = err.config
        if (err && err.response.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true
            return getNewToken().then((token: any) => {
                if (token.accessToken) {
                    const headers: any = {
                        'ScreenAccessToken': token.accessToken,
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'tokenkey': token.keystr,
                    }
                    originalRequest.headers = headers
                    sessionStorage.setItem("tokenkey", token.keystr)
                    window.sessionStorage.setItem('ScreenToken', token.accessToken)
                }
                console.log(err)
                return axios(err.config)
            }).catch((error: any) => {

                return Promise.reject(error)
            })
        }
        return Promise.reject(err)
    }
})
// export default Server;
// 重新获取token
function getNewToken() {
    var promise = new Promise(function (resolve, reject) {
        axios.post('/api/screen/2NyZWIjoxNzE3VuIiwiaWF0/reloadToken')
            .then(res => {
                console.log(res.data.data.accessToken)
                resolve(res.data.data)
            }).catch(err => {
                reject(err)
            })
    })
    return promise
}
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url: string, params?: object | string) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url: string, params?: object | string, config?: any) {
    return new Promise((resolve, reject) => {
        axios.post(url, params, config)
            .then(res => {
                if (config) {
                    resolve(res)
                } else {
                    resolve(res.data)
                }
            })
            .catch(err => {
                reject(err.data)
            })
    })
}
/**
 * put方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function put(url: string, params?: object | string) {
    return new Promise((resolve, reject) => {
        axios.put(url, params)
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err.data)
            })
    })
}
/**
 * delete方法，对应delete请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function delete2(url: string, params?: object | string) {
    return new Promise((resolve, reject) => {
        axios.delete(url, {
            params: params
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}